package com.xingongchang.baolebei.activity;

import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import com.external.androidquery.callback.AjaxStatus;
import com.insthub.BeeFramework.activity.BaseActivity;
import com.insthub.BeeFramework.model.BusinessResponse;
import com.insthub.BeeFramework.view.ToastView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.model.ProtocolConst;
import com.xingongchang.baolebei.model.UserInfoModel;
import com.xingongchang.baolebei.photo.Bimp;
import com.xingongchang.baolebei.photo.FileUtils;
import com.xingongchang.baolebei.photo.PhotoActivity;
import com.xingongchang.baolebei.protocol.USER_INFO;
/**
 * 发帖页面
 * @author haha
 *
 */
public class SendTopicActivity extends BaseActivity implements BusinessResponse {

	private ImageView backButton;
	private TextView title;
	private LinearLayout top_right_button;
	private TextView top_right_text;
	public USER_INFO userinfo;
	private UserInfoModel mUserInfoModel;
	ImageLoader imageLoader = ImageLoader.getInstance();
	JSONArray jsonarray = new JSONArray();
	String pic = "";
	private GridView photos;
	private GridAdapter adapter;
	EditText topic_body, topic_title;
	public final int TEXT_MAX = 5000;
	String topicTitle = "";
	String topicBody = "";
	ProgressDialog pd;
	boolean booleans=false;
	int cat_id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sendtopic);
		cat_id=getIntent().getIntExtra("catId", 100);
		findViewById();
		setListener();
		init();
	}

	private void findViewById() {
		backButton = (ImageView) findViewById(R.id.top_view_back);
		title = (TextView) findViewById(R.id.top_view_text);
		top_right_button = (LinearLayout) findViewById(R.id.top_right_button);
		top_right_text = (TextView) findViewById(R.id.top_right_text);
		topic_title = (EditText) findViewById(R.id.topic_title);
		topic_body = (EditText) findViewById(R.id.topic_body);
	}

	private void setListener() {

		backButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				Bimp.bmp.clear();
				Bimp.drr.clear();
				Bimp.max = 0;
				FileUtils.deleteDir();
				finish();
			}
		});

		top_right_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				processThread();
			}
		});

		// 输入框限制输入字数
		topic_body.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
			private int selectionStart;
			private int selectionEnd;

			@Override
			public void beforeTextChanged(CharSequence s, int arg1, int arg2,
					int arg3) {
				temp = s;
			}

			@Override
			public void onTextChanged(CharSequence s, int arg1, int arg2,
					int arg3) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				selectionStart = topic_body.getSelectionStart();
				selectionEnd = topic_body.getSelectionEnd();
				if (temp.length() > TEXT_MAX) {
					Toast.makeText(SendTopicActivity.this, "文字不能超出5000字",
							Toast.LENGTH_SHORT).show();
					s.delete(selectionStart - 1, selectionEnd);
					int tempSelection = selectionStart;
					topic_body.setText(s);
					topic_body.setSelection(tempSelection);
				}
			}

		});

	}

	protected void processThread() {
		// TODO Auto-generated method stub
		// 构建一个下载进度条
		pd = ProgressDialog.show(SendTopicActivity.this, "上传图片", "数据处理中...");
		new Thread() {
			@Override
			public void run() {
				// 在新线程里执行长耗时方法
				longTimeMethod();
				// 执行完毕后给handler发送一个空消息
				handler.sendEmptyMessage(0);
			}
		}.start();
	}

	private Handler handler = new Handler() {
		// 当有消息发送出来的时候就执行Handler的这个方法
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			// 只要执行到这里就关闭对话框
			pd.dismiss();
//			pic = jsonarray.toString();
			topicTitle = topic_title.getText().toString().trim();
			topicBody = topic_body.getText().toString().trim();
			if (topicTitle.equals("")) {
				Toast.makeText(SendTopicActivity.this, "标题不能为空",
						Toast.LENGTH_SHORT).show();
				return;
			} else if (topicBody.equals("")) {
				Toast.makeText(SendTopicActivity.this, "帖子内容不能为空",
						Toast.LENGTH_SHORT).show();
				return;
			}
				mUserInfoModel.sendTopic(topicTitle, topicBody, jsonarray,cat_id);
				
		}

	};

	// 执行长耗时方法
	protected void longTimeMethod() {
		int count = 0;
		for (int i = 0; i < Bimp.bmp.size(); i++) {
			Bitmap bm = Bimp.bmp.get(i);
			String img = imgToBase64("", bm, "");
			if(!img.equals("")){
				try {
					JSONObject jsonObj = new JSONObject();
					jsonObj.put("img", img);
					jsonarray.put(jsonObj);
					count ++ ;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(count == Bimp.bmp.size()){
					return;
				}
			}
		
			
		}
//			Thread.sleep(10000);
	}

	private void init() {

		backButton.setVisibility(View.VISIBLE);
		top_right_button.setVisibility(View.VISIBLE);
		title.setText("发布帖子");
		top_right_text.setText("发布");
		photos = (GridView) findViewById(R.id.photoGridview);
		photos.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(SendTopicActivity.this);
		adapter.update();
		photos.setAdapter(adapter);
		photos.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (position == Bimp.bmp.size()) {
					dialogNote();
				} else {
					Intent intent = new Intent(SendTopicActivity.this,
							PhotoActivity.class);
					intent.putExtra("ID", position);
					startActivity(intent);
				}
			}
		});
		mUserInfoModel = new UserInfoModel(this);
		mUserInfoModel.addResponseListener(this);

	}

	public class GridAdapter extends BaseAdapter {

		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			return (Bimp.bmp.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder = null;
			if (convertView == null) {

				convertView = inflater.inflate(R.layout.album_item, parent,
						false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == Bimp.bmp.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.btn_addpic));
				if (position == 8) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.bmp.get(position));
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			new Thread(new Runnable() {
				public void run() {

					while (true) {
						if (Bimp.max == Bimp.drr.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							try {
								String path = Bimp.drr.get(Bimp.max);
								Bitmap bm = Bimp.revitionImageSize(path);
								Bimp.bmp.add(bm);
								String newStr = path.substring(
										path.lastIndexOf("/") + 1,
										path.lastIndexOf("."));
								FileUtils.saveBitmap(bm, "" + newStr);
								Bimp.max += 1;
								Message message = new Message();
								message.what = 1;
								handler.sendMessage(message);
							} catch (IOException e) {

								e.printStackTrace();
							}
						}
					}
				}
			}).start();
		}
	}

	protected void onRestart() {
		adapter.update();
		super.onRestart();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == PHOTO_REQUEST_CAREMA) {
			// 从相机返回的数据
//			if (data != null) {
				// Bitmap bitmap = data.getParcelableExtra("data");
			String path = Environment.getExternalStorageDirectory() + "/"
					+ PHOTO_FILE_NAME;
			Bimp.drr.add(path);
//			}
			// if (hasSdcard()) {
			// crop(Uri.fromFile(tempFile));
			// } else {
			// Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT)
			// .show();
			// }
		} else if (requestCode == PHOTO_REQUEST_CUT) {
			// 从剪切图片返回的数据
			// if (data != null) {
			// // Bitmap bitmap = data.getParcelableExtra("data");
			// Bimp.drr.add(Environment.getExternalStorageDirectory() + "/"
			// + PHOTO_FILE_NAME);
			// }
			// try {
			// // 将临时文件删除
			// tempFile.delete();
			// } catch (Exception e) {
			// e.printStackTrace();
			// }

		}
	}

	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		// TODO Auto-generated method stub
		if (url.endsWith(ProtocolConst.SEND_TOPIC)) {
			Bimp.bmp.clear();
			Bimp.drr.clear();
			Bimp.max = 0;
			FileUtils.deleteDir();
			if(mUserInfoModel.responseStatus.succeed==1){
				booleans=true;
				if(booleans==true){
					ToastView toast = new ToastView(SendTopicActivity.this, "帖子发布成功");
			        toast.setGravity(Gravity.CENTER, 0, 0);
			        toast.show();
				}
				finish();
			}
//			}else{
//		       Toast.makeText(getApplicationContext(), "", 0).show();
//			}
		}

	}

}
